package com.egg.ylt.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.DividerItemDecoration;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.activity.ACT_BabyManage;
import com.egg.ylt.activity.ACT_HistoryData;
import com.egg.ylt.activity.ACT_ScanCode;
import com.egg.ylt.activity.ACT_UserLogin;
import com.egg.ylt.activity.health.ACT_UpdateShop;
import com.egg.ylt.adapter.ADA_HealthAirAdapter;
import com.egg.ylt.adapter.ADA_HealthWaterAdapter;
import com.egg.ylt.datePicker.CustomDatePicker;
import com.egg.ylt.pojo.BindEquipmentStatusEntity;
import com.egg.ylt.pojo.CaloriesEntity;
import com.egg.ylt.pojo.RealtimeDataEntity;
import com.egg.ylt.pojo.UpdateShopEventBean;
import com.egg.ylt.presenter.impl.HealthPresenterImpl;
import com.egg.ylt.view.IHealthDataView;
import com.yonyou.framework.library.base.BaseFragment;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.ListUtil;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.eventbus.EventCenter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sichaoqi on 2018/9/3.
 */

public class FRA_HealthData extends BaseFragment<HealthPresenterImpl> implements IHealthDataView {
    @BindView(R.id.tv_shop_date)
    TextView tvShopDate;
    @BindView(R.id.tv_baby_info)
    TextView tvBabyInfo;
    @BindView(R.id.tv_bind_swim)
    TextView tvBindSwim;
    @BindView(R.id.tv_swim_calorie)
    TextView tvSwimCalorie;
    @BindView(R.id.tv_swim_time)
    TextView tvSwimTime;
    @BindView(R.id.tv_water)
    TextView tvWater;
    @BindView(R.id.water_recycler_view)
    RecyclerView waterRecyclerView;
    @BindView(R.id.tv_air)
    TextView tvAir;
    @BindView(R.id.air_recycler_view)
    RecyclerView airRecyclerView;
    @BindView(R.id.rl_loading_target)
    RelativeLayout rlLoadingTarget;
    @BindView(R.id.tv_swim)
    TextView tvSwim;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.iv_health_gif)
    ImageView ivHealthGif;

    private ADA_HealthWaterAdapter waterAdapter;
    private ADA_HealthAirAdapter airAdapter;
    private Task task;
    private Timer timer;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private CustomDatePicker customDatePicker2;
    private AppSharedPreferences mSp;
    private String babyId;
    private String mCode;
    private boolean babyStatus = false;

    private String mStatus;

    private String mShopId = "";
    private String mShopName = "广东宝贝游吧斗门店";

    public final static int CHANGE_SWIM_REQUEST = 0x001;

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    protected void onFirstUserVisible() {

    }

    @Override
    protected void onUserVisible() {
        if (mPresenter != null){
            getBabyContent();
        }
    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    protected View getLoadingTargetView() {
        return rlLoadingTarget;
    }

    @Override
    protected void initViewsAndEvents() {
        //设置时间选择器
        initDataPicker();

        //获取本地用户宝宝默认的ID
        getBabyContent();

        //初始化recyclerview
        initRecycler();

        //设置轮询时间间隔
        timer = new Timer();
        task = new Task();
        //schedule 计划安排，时间表 1 我们第2 步定义TimerTask类，2 表示的意思是我们需要多长时间
        //执行我们的TimerTask类中run方法，3 设置轮询间隔的时间
        timer.schedule(task, 1000, 4 * 1000);

        // 加载gif
        Glide.with(this).load(R.mipmap.ic_heath_gif).into(ivHealthGif);

    }

    private void getBabyContent() {
        mSp = new AppSharedPreferences(mContext);
        babyId = mSp.getString(Constants.BABY_ID);
        if (StringUtil.isEmpty(babyId)) {
            setTextViewImg(tvBabyInfo, R.mipmap.healthdata_icon_babayinfo_default);
        } else {
            setTextViewImg(tvBabyInfo, R.mipmap.healthdata_icon_babayinfo_click);
        }
        mCode = mSp.getString(Constants.SWIM_RING_ID);
        //检查宝宝是否绑定设备
        mPresenter.getBabyStatus(Constants.TOKEN, babyId, mCode);
    }


    /**
     * 初始化时间选择器
     */
    private void initDataPicker() {

        tvShopDate.setText(getDate());

        customDatePicker2 = new CustomDatePicker(mContext, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                String mDate = time.split(" ")[0];
                tvShopDate.setText(mDate);
                Bundle mBundle = new Bundle();
                mBundle.putString("date", mDate);
                readyGo(ACT_HistoryData.class, mBundle);
            }
        }, "2010-01-01 00:00", "2030-01-01 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker2.showSpecificTime(false); // 显示时和分
        customDatePicker2.setIsLoop(true); // 允许循环滚动
    }

    private void initRecycler() {
        //水质   设置布局管理器
        GridLayoutManager waterManager = new GridLayoutManager(mContext, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        //设置分割线
        waterRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, 1));
        waterRecyclerView.setLayoutManager(waterManager);
        //设置适配器
        waterAdapter = new ADA_HealthWaterAdapter(mContext);
        waterRecyclerView.setAdapter(waterAdapter);

        //空气 设置布局管理器
        GridLayoutManager airManager = new GridLayoutManager(mContext, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        //设置分割线
        airRecyclerView.addItemDecoration(new DividerItemDecoration(mContext,
                1));
        airRecyclerView.setLayoutManager(airManager);
        //设置适配器
        airAdapter = new ADA_HealthAirAdapter(mContext);
        airRecyclerView.setAdapter(airAdapter);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fra_health_data;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()){
            case Constants.UPDATE_SHOP_EVENT:
                UpdateShopEventBean data = (UpdateShopEventBean)eventCenter.getData();
                mShopId = data.getShopId();
                mShopName = data.getShopName();
                tvShopName.setText(mShopName);
                break;
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    public void getData(RealtimeDataEntity entity) {
        if (entity == null) {
            return;
        }
        //空气
        if (!ListUtil.isListEmpty(entity.getAir())) {
            airAdapter.setDataList(entity.getAir());
        }
        //水质
        if (!ListUtil.isListEmpty(entity.getWater())) {
            waterAdapter.setDataList(entity.getWater());
        }
    }

    @Override
    public void getBabyData(CaloriesEntity entity) {
        //获取宝宝卡路里数据
        if (entity == null) {
            return;
        }
        mStatus = entity.getStatus();
        if ("1".equals(entity.getStatus())) {
            babyStatus = false;
            setTextViewImg(tvBindSwim, R.mipmap.healthdata_icon_swimmingring_default);
            return;
        }else{
            setTextViewImg(tvBindSwim, R.mipmap.healthdata_icon_swimmingring_click);
        }
        //千卡
        tvSwimCalorie.setText(entity.getCalories());
        //时间
        tvSwimTime.setText(entity.getTime() + "分钟");
    }

    @Override
    public void getStatus(BindEquipmentStatusEntity entity) {
        //获取游泳圈绑定状态
        if (entity == null) {
            return;
        }
        //0 绑定；1 未绑定
        mStatus = entity.getStatus();
        if ("0".equals(entity.getStatus())) {
            tvSwim.setText("消耗卡路里");
            babyStatus = true;
            setTextViewImg(tvBindSwim, R.mipmap.healthdata_icon_swimmingring_click);
        } else {
            tvSwim.setText("消耗卡路里");
            setTextViewImg(tvBindSwim, R.mipmap.healthdata_icon_swimmingring_default);
        }
    }

    /**
     * 给textview设置top图片
     * @param tv
     * @param imgId
     */
    public void setTextViewImg(TextView tv, int imgId){
        Drawable drawableTop = getActivity().getResources().getDrawable(imgId);
        tv.setCompoundDrawablesWithIntrinsicBounds(null,
                drawableTop, null, null);
    }

    //轮询请求实时数据
    class Task extends TimerTask {
        @Override
        public void run() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    //请求游泳馆水质 空气数据
                    mPresenter.getRealtimeData(Constants.COMPANYID, mShopId);
                    //请求宝宝消耗的卡路里数据
                    if (babyStatus) {
                        if (!StringUtil.isEmpty(babyId) && !StringUtil.isEmpty(mCode)) {
                            mPresenter.getBabyCalories(Constants.TOKEN, babyId, mCode);
                        }
                    }

                }
            });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
    }

    @OnClick({R.id.tv_shop_date, R.id.tv_baby_info, R.id.tv_bind_swim, R.id.tv_update_shop})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_shop_date://时间
                customDatePicker2.show(getDate());
                break;
            case R.id.tv_baby_info://去选择宝宝
                if (StringUtil.isEmpty(Constants.TOKEN)) {
                    readyGo(ACT_UserLogin.class);
                } else {
                    readyGo(ACT_BabyManage.class);
                }
                break;
            case R.id.tv_bind_swim://绑定游泳圈
                if ("0".equals(mStatus)) {
                    ToastUtil.makeText(mContext, "您已经绑定了泳圈设备", false);
                    return;
                }
                readyGo(ACT_ScanCode.class);
                break;
            case R.id.tv_update_shop://切换游泳馆
                readyGoForResult(ACT_UpdateShop.class, CHANGE_SWIM_REQUEST);
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    /**
     * 获取当前时间
     */
    public String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        String time = sdf.format(new Date());
        return time;
    }

}
